package com.hs.srm.admin.modules.quota.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.hs.srm.admin.modules.pricemanagement.service.EssentialInformationService;
import com.hs.srm.admin.modules.quota.entity.QuotaEntity;
import com.hs.srm.admin.modules.quota.service.QuotaHistoryService;
import com.hs.srm.admin.modules.quota.service.QuotaService;
import com.hs.srm.admin.modules.ssess.service.SsessService;
import com.hs.srm.admin.modules.ssess.vo.SsessVO;
import com.hs.srm.admin.modules.sys.controller.AbstractController;
import com.hs.srm.base.common.annotation.SysLog;
import com.hs.srm.base.common.config.SysConfig;
import com.hs.srm.common.utils.DateUtils;
import com.hs.srm.common.utils.PageUtils;
import com.hs.srm.common.utils.R;
import com.hs.srm.tools.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import sunnykid.text.SunnykidText;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author yanfei
 * @date 2019年4月2日
 * 配额数据
 */
@RestController
@RequestMapping("/quota")
public class QuotaController extends AbstractController {


    private static final long serialVersionUID = 1L;

    @Autowired
    private QuotaService quotaService;

    @Autowired
    private QuotaHistoryService quotaHistoryService;

    @Autowired
    private EssentialInformationService essentialInformationService;

    @Autowired
    private SsessService ssessService;

    /**
     * 查询配额信息
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = this.quotaService.queryPage(params);
        return R.ok(page);
    }

    /**
     * 查询配额历史记录信息
     */
    @RequestMapping("/historyList")
    public R historyList(@RequestParam Map<String, Object> params) {
        PageUtils page = this.quotaHistoryService.queryPage(params);
        return R.ok(page);
    }

    /**
     * 配额保存
     */
    @SysLog("编辑配额")
    @RequestMapping(value = "/save")
    @RequiresPermissions("quota:save")
    public R save(QuotaEntity quotaEntity) {
        if (quotaEntity == null) {
            return R.error();
        }
        QuotaEntity qentity = this.quotaService.selectById(quotaEntity);
        //配额数小于已用配额量
        if (StringUtils.isNotBlank(quotaEntity.getQuotaId()) && quotaEntity.getQuotaNum().compareTo(qentity.getUsedQuotaNum()) < 0) {
            return R.error();
        }
        quotaEntity.setCreationDate(new Date());
        //创建者
        quotaEntity.setCreatedBy(this.getUser().getUsername());
        this.quotaService.insertOrUpdate(quotaEntity);
        return R.ok();
    }

    /**
     * 跳转到配额管理编辑页面
     *
     * @param
     * @return
     */
    @RequestMapping("/toEdit/{quotaId}")
    public ModelAndView toEdit(@PathVariable("quotaId") String quotaId) {
        QuotaEntity quotaEntity = this.quotaService.selectById(quotaId);

        // 把查询出来的对象赋值给供应商实体
        ModelAndView modelAndView = new ModelAndView("modules/quota/quota_edit");
        modelAndView.addObject("quotaEntity", quotaEntity);
        return modelAndView;
    }

    /**
     * 计算月度配额 (月度配额)
     */
    public void EssentialInformation() {
        //Map<String,BigDecimal> map = new HashMap<String, BigDecimal>();
        //Map<String,BigDecimal> map1 = new HashMap<String, BigDecimal>();
        /**********************配额根据月度评分的上月分数来得出配额***********************************/
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-01 00:00:00");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, -1);
        int lastMonthMaxDay = c.getActualMaximum(Calendar.DAY_OF_MONTH);
        c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), lastMonthMaxDay, 23, 59, 59);
        //按格式输出
        String gtime2 = sdf2.format(c.getTime()); //上月第一天
        String gtime = sdf.format(c.getTime()); //上月最后一天
        Date begintime = DateUtils.stringToDate(gtime2, DateUtils.DATE_TIME_PATTERN);
        Date endtime = DateUtils.stringToDate(gtime, DateUtils.DATE_TIME_PATTERN);
        /**********************配额根据月度评分的上月分数来得出配额***********************************/
        List<SsessVO> list = this.ssessService.findBySsessAndQuota(begintime, endtime);
        //List<String> strlisttem = new ArrayList<String>();
        //List<String> strlist = new ArrayList<String>();
        //QuotaEntity quota = new QuotaEntity();
        //总分
        //BigDecimal Qty = BigDecimal.ONE;
        if (list.size() > 0) {
            for (SsessVO ssvo : list) {
                QuotaEntity quota = new QuotaEntity();
                quota.setQuotaId(SunnykidText.getUUID());
                quota.setMaterialCode(ssvo.getMaterialCode());
                quota.setMaterialDesc(ssvo.getMaterialDesc());
                quota.setCreationDate(DateUtils.currentDateTime());
                //quota.setCreatedBy(this.getUser().getName());
                quota.setVendorCode(ssvo.getVendorCode());
                quota.setVendorName(ssvo.getVendorName());
                quota.setWerks(ssvo.getWerks());
                this.quotaService.insert(quota);
            }
        }
    }

    /**
     * 根据vendorCode、materialCode查询是否存在
     * 相同vendorCode、materialCode已存在记录的end_date要小于新增记录的开始时间
     *
     * @param vendorCode
     * @param materialCode
     * @return
     */
    @PostMapping("/checkExist")
    public R checkExist(String vendorCode, String materialCode, String startDate, String werks) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<QuotaEntity> list = quotaService.selectList(new EntityWrapper<QuotaEntity>()
                .eq("vendor_code", vendorCode)
                .eq("material_code", materialCode)
                .eq("werks", werks));

        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getStartDate() == null) {
                return R.error("已存在该记录，可直接修改！");
            } else if (list.get(i).getEndDate().compareTo(format.parse(startDate)) >= 0) {
                return R.error("开始日期不能小于已存在记录的结束日期！");
            }
        }
        return R.ok();
    }

    /**
     * 删除配额信息
     */
    @SysLog("删除配额信息")
    @RequestMapping("/delete")
    public R delete(@RequestParam("quotaId[]") String[] quotaId) {
        boolean b = quotaService.deleteBatchIds(Arrays.asList(quotaId));
        if (!b) {
            return R.error();
        }
        return R.ok();

    }

    /**
     * 配额数据模板导入
     *
     * @param multipartFile
     * @return
     */
    @PostMapping("/importQuotaData")
    public R importQuotaData(@RequestParam("importFile") MultipartFile multipartFile) {
        //上传文件，保存在临时文件夹下
        String filePath = SysConfig.getUploadPath() + "/temp/" + multipartFile.getOriginalFilename();
        FileUtils.fileUpload(SysConfig.getUploadPath() + "/temp/", multipartFile.getOriginalFilename(), multipartFile);
        File file = new File(filePath);
        //导入文件中的配额数据,返回导入数据行数
        Map<String, Object> resultMap = quotaService.importQuotaData(file, this.getUser().getName());
        //删除临时文件
        file.delete();
        return R.ok(resultMap);
    }
}
